<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
    <div id="container" class="container">
        <iframe id="editor" class="editor">
        </iframe>
        <div style="clear:both">
            <div id="scrollLock" class="page-button"> </div>
            <div id="save" class="page-button"></div>
            <div id="print" class="page-button"></div>
            <div id="clear" class="page-button"></div>
            <div id="link" class="page-button"></div>
            <div id="style" class="page-button"></div>
            <div id="color" class="page-button"></div>
            <div id="help" class="page-button"></div>
        </div>
        <iframe id="preview" class="preview" style="margin-left: auto;">
        </iframe>
    </div>
    <div id="messageListContainer" class="message-list-container">
    </div>

    </div>
    <script type="module">
        import { personalInformation } from "./personalInformation.js"
        import { educationExperience } from "./educationExperience.js"
        import { award } from "./award.js"
        import { personalSkill } from "./personalSkill.js"
        import { workExperience } from "./workExperience.js"
        import { projectExperience } from "./projectExperience.js"
        import { readAsStringAsync } from "./fileReader.js"
        import { findTitle, split, removeATag, expandATag } from "./baseMatcher.js"
        import { bindJumperByPosition, setLinkBehavior } from "./postRenderer.js"
        import {
            loadLinksTo,
            removeLinksFrom,
            createScrollLockIcon,
            createScrollUnlockIcon,
            createSaveIcon,
            createPrintIcon,
            createClearIcon,
            createLinkIcon,
            createHideLinkIcon,
            createDetailLinkIcon,
            createStyleIcon,
            createFullColorIcon,
            createGrayColorIcon,
            createHelpIcon,
            initMessageList,
            showMessage
        } from "./uiCreator.js"
        let str = "";
        let editor = document.getElementById('editor');
        let preview = document.getElementById('preview');

        let editorWindow = editor.contentWindow;
        let previewWindow = preview.contentWindow;

        let scrollTarget = null;
        let scrollLock = true;
        let showLink = 0;

        let fullColor = true;

        let styles = ["main", "autumn", "simple"]
        let styleIndex = 0

        let editorDoc = editorWindow.document;
        let previewDoc = previewWindow.document;

        function loadStyle(style, clear) {
            loadLinksTo(document, [
                `css/${style}/icon.css`,
                `css/${style}/page.css`,
                `css/${style}/message.css`
            ], clear)
            loadLinksTo(editorDoc, [
                `css/${style}/editor.css`
            ], clear)
            loadLinksTo(previewDoc, [
                `css/${style}/preview/preview.css`,
                `css/${style}/preview/personalInformation.css`,
                `css/${style}/preview/educationExperience.css`,
                `css/${style}/preview/award.css`,
                `css/${style}/preview/workExperience.css`,
                `css/${style}/preview/projectExperience.css`,
                `css/${style}/preview/personalSkill.css`,
            ], clear)
        }
        // loadLinksTo(document, [
        //     `css/main/icon.css`,
        //     `css/main/page.css`,
        //     `css/main/message.css`
        // ])
        loadStyle(styles[styleIndex])
        let scrollLockHTML = ""
        let scrollUnlockHTML = ""
        let showLinkHTML = ""
        let hideLinkHTML = ""
        let detailLinkHTML = ""
        let fullColorHTML = ""
        let grayColorHTML = ""

        let editorArea = editorDoc.createElement('textarea');
        editorArea.setAttribute('contenteditable', true);
        editorArea.setAttribute('user-modify', "read-write-plaintext-only");
        editorArea.className = "area";
        editorDoc.body.appendChild(editorArea);

        let scrollLockButton = document.getElementById("scrollLock");
        let saveButton = document.getElementById("save");
        let printButton = document.getElementById("print");
        let clearButton = document.getElementById("clear");
        let linkButton = document.getElementById("link");
        let styleButton = document.getElementById("style");
        let colorButton = document.getElementById("color");
        let helpButton = document.getElementById("help");

        let messageList = initMessageList(document.getElementById('messageListContainer'))

        window.addEventListener('load', async function () {
            if (localStorage.getItem("myVitae") != null && localStorage.getItem("myVitae") != undefined) {
                str = localStorage.getItem("myVitae")
            }
            else {
                str = await readAsStringAsync("./MyVitae.md");
            }
            scrollLockHTML = await createScrollLockIcon(scrollLockButton)
            scrollUnlockHTML = await createScrollUnlockIcon()
            showLinkHTML = await createLinkIcon(linkButton)
            hideLinkHTML = await createHideLinkIcon()
            detailLinkHTML = await createDetailLinkIcon()
            fullColorHTML = await createFullColorIcon(colorButton)
            grayColorHTML = await createGrayColorIcon()
            editorArea.value = str;
            render(str)
        })

        editorDoc.addEventListener('keydown', function (event) {
            if ((event.key == 'p' || event.key == 'P') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {// ctrl+p
                event.preventDefault();
                previewWindow.print()
            } else if ((event.key == 's' || event.key == 'S') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {//ctrl+s
                event.preventDefault();
                localStorage.setItem("myVitae", editorArea.value)
            } else if ((event.key === '/') && (event.ctrlKey || event.metaKey)) {
                event.preventDefault();
                showMessage(messageList, "按下了注释，此功能未实现")
            }
        })
        previewDoc.addEventListener('keydown', function (event) {
            if ((event.key == 'p' || event.key == 'P') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {// ctrl+p
                event.preventDefault();
                previewWindow.print()
            }
            else if ((event.key == 's' || event.key == 'S') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {//ctrl+s
                event.preventDefault();
                localStorage.setItem("myVitae", editorArea.value)
            }
        })
        document.addEventListener('keydown', function (event) {
            if ((event.key == 'p' || event.key == 'P') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {// ctrl+p
                event.preventDefault();
                previewWindow.print()
            }
            else if ((event.key == 's' || event.key == 'S') && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {//ctrl+s
                event.preventDefault();
                localStorage.setItem("myVitae", editorArea.value)
            }
        })
        editorArea.addEventListener('mouseover', function (event) {
            scrollTarget = editorArea;
        })
        previewWindow.addEventListener('mouseover', function (event) {
            scrollTarget = previewWindow;
        })

        editorArea.addEventListener('scroll', function (event) {
            if (scrollLock && scrollTarget === editorArea) {
                previewWindow.scroll({
                    top: editorArea.scrollTop * (previewDoc.body.scrollHeight - previewDoc.body.clientHeight) / (editorArea.scrollHeight - editorArea.clientHeight),
                });
            }
        })
        previewWindow.addEventListener('scroll', function (event) {
            if (scrollLock && scrollTarget === previewWindow) {
                editorArea.scroll({
                    top: previewWindow.scrollY * (editorArea.scrollHeight - editorArea.clientHeight) / (previewDoc.body.scrollHeight - previewDoc.body.clientHeight),
                });
            }
        })

        editorArea.addEventListener('keyup', function () {
            str = editorArea.value;
            render(str)
        })

        scrollLockButton.addEventListener("click", function (event) {
            if (scrollLock) {
                showMessage(messageList, "解锁同步滚动")
                scrollLockButton.innerHTML = scrollUnlockHTML;
            }
            else {
                showMessage(messageList, "锁定同步滚动")
                scrollLockButton.innerHTML = scrollLockHTML;
            }
            scrollLock = !scrollLock;
        })

        createSaveIcon(saveButton);
        saveButton.addEventListener("click", function (event) {
            showMessage(messageList, "保存到localStorage")
            localStorage.setItem("myVitae", editorArea.value)
        })

        createPrintIcon(printButton);
        printButton.addEventListener("click", function (event) {
            previewWindow.print();
        })

        createClearIcon(clearButton);
        clearButton.addEventListener("click", async function (event) {
            showMessage(messageList, "清除localStorage")
            localStorage.removeItem("myVitae");
            let str = await readAsStringAsync("./MyVitae.md");
            editorArea.value = str;
            render(str)
        })

        createHelpIcon(helpButton);
        helpButton.addEventListener("click", function (event) {
            const helpTextList = [
                `点击我显示各种提示`,
                `点击气泡可以将其消除`,
                `点击 🔒/🔓 以锁定/解锁双向滚动`,
                `双击右侧渲染内容可看到对应的原始markdown内容`,
                `点击 💾 可以保存内容到localStorage`,
                `点击 🖨️ 可以打印简历为pdf`,
                `点击 🚮 可以清除localStorage的缓存`,
                `多次点击 🔗 可以切换简历中对链接的显示策略`,
                `点击 数字按钮 可以切换渲染风格`,
                `点击 🌈 可以切换彩色/灰度显示`
            ]
            let targetIndex = 0;
            if (helpButton.dataset.previousIndex) {
                let randomIndex = parseInt(Math.floor(Math.random() * (helpTextList.length - 1))) + 1;
                let previousIndex = parseInt(helpButton.dataset.previousIndex);
                if (randomIndex == previousIndex) {
                    randomIndex += 1;
                    if (randomIndex == helpTextList.length) {
                        randomIndex = 1;
                    }
                }
                helpButton.dataset.previousIndex = randomIndex;
                targetIndex = randomIndex;
            } else {
                helpButton.dataset.previousIndex = targetIndex;
            }
            switch (event.button) {
                case 0://lclick
                    showMessage(messageList, `❓ ${helpTextList[targetIndex]}`, 10000)
                    break;
                case 2://rclick
                    break;
            }

        })

        linkButton.addEventListener("click", function (event) {
            showLink += 1;
            showLink %= 3;
            switch (showLink) {
                case 0:
                    linkButton.innerHTML = showLinkHTML;
                    showMessage(messageList, "显示链接")
                    break;
                case 1:
                    linkButton.innerHTML = hideLinkHTML;
                    showMessage(messageList, "隐藏链接");
                    break;
                case 2:
                    linkButton.innerHTML = detailLinkHTML;
                    showMessage(messageList, "显示详细链接");
                    break;
            }
            render(str)
        })

        createStyleIcon(styleButton);
        styleButton.addEventListener("click", function (event) {
            styleIndex += 1;
            styleIndex %= styles.length;
            styleButton.getElementsByTagName('text')[0].innerHTML = styleIndex
            loadStyle(styles[styleIndex])
            showMessage(messageList, `风格切换到 ${styles[styleIndex]}`)
        })

        colorButton.addEventListener("click", function (event) {
            fullColor = !fullColor;
            if (fullColor) {
                colorButton.innerHTML = fullColorHTML;
                showMessage(messageList, "彩色显示");
                removeLinksFrom(previewDoc, `css/${styles[styleIndex]}/preview/gray.css`)
            } else {
                colorButton.innerHTML = grayColorHTML;
                showMessage(messageList, "灰度显示，注意该显示仅供黑白打印机的纸质打印效果预览，不能作用到pdf文件");
                loadLinksTo(previewDoc, `css/${styles[styleIndex]}/preview/gray.css`)
            }
        })

        function render(str, option) {
            if (!option) {
                option = {
                    showLink: showLink
                }
            }
            previewDoc.body.innerHTML = "";
            let subTokens = split(str)
            let titleModuleMap = {
                "个人信息": personalInformation,
                "教育经历": educationExperience,
                "获奖经历": award,
                "个人技能": personalSkill,
                "工作经历": workExperience,
                "项目经历": projectExperience,
            }
            // TODO: 排序与别名的适配
            // let moduleOrder = [
            //     "个人信息",
            //     "教育经历",
            //     "获奖经历",
            //     "个人技能",
            //     "工作经历",
            //     "项目经历"
            // ]
            // for (let key of moduleOrder) {
            for (let item of subTokens) {
                if (titleModuleMap[item.type] != null) {
                    previewDoc.body.appendChild(
                        titleModuleMap[item.type].render(
                            titleModuleMap[item.type].parse(
                                item.tokens
                            ),
                            option
                        )
                    )
                }
            }
            // }
            switch (option.showLink) {
                case 0:
                    break;
                case 1:
                    removeATag(previewDoc);
                    break;
                case 2:
                    expandATag(previewDoc);
                    break;
            }
            bindJumperByPosition(editorArea, previewDoc);
            setLinkBehavior(previewDoc);
        }

    </script>

</body>

</html>